package com.cxhd.lis.ws;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.DefaultFileRegion;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;

import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import io.netty.handler.ssl.SslHandler;
import io.netty.handler.stream.ChunkedNioFile;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.URISyntaxException;
import java.net.URL;

/**
 * 处理 Http 请求
 * @author waylau.com
 * @date 2015-3-26 
 */
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> { //1
    private final String wsUri;

    private BaseServer server;



    public HttpRequestHandler(String wsUri,BaseServer server) {
        this.wsUri = wsUri;
        this.server=server;
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {

        if (req.getUri().startsWith(wsUri)) {

            ctx.fireChannelRead(req.retain());
            onOpen(ctx,req);
        } else {
            if (HttpHeaders.is100ContinueExpected(req)) {
                send100Continue(ctx);                               //3
            }
          
//           if (req.getUri().equals("/")) {
//             ResponseWrite.sendHttpContent(ctx, req, "你想看什么？");
//            return;
//        } 
//           else if (req.getUri().startsWith("/app") && req.getUri().contains(".data")) {
//          
//            try {
//                server.httpReq(ctx, req, null);
//            } catch (Exception e) {
//                e.printStackTrace();
//                ResponseWrite.sendHttp505(ctx, req, e);
//            }
//            return;
//            //  queryStringDecoder.getParameters()
//        } else{
//            // ResponseWrite.sendHttp404(ctx, req);
//        }
        }
    }

    private static void send100Continue(ChannelHandlerContext ctx) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE);
        ctx.writeAndFlush(response);
    }

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
    	Channel incoming = ctx.channel();
		System.out.println("Client:"+incoming.remoteAddress()+"异常");
        // 当出现异常就关闭连接
        cause.printStackTrace();

        ctx.close();
	}
    public void onOpen(ChannelHandlerContext ctx, HttpRequest req) {
        server.onOpen(ctx, req);
        //ctx.getChannel().
    }
}
